package com.arvin.faceDetect.utils

import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Looper
import android.view.LayoutInflater
import android.widget.TextView
import com.arvin.faceDetect.R
import java.io.PrintWriter
import java.io.StringWriter
import java.text.SimpleDateFormat
import java.util.*
import kotlin.system.exitProcess

class CrashHandler private constructor() : Thread.UncaughtExceptionHandler {
    private var mContext: Context? = null
    private var mDefaultHandler: Thread.UncaughtExceptionHandler? = null

    companion object {
        private val instance = CrashHandler()

        fun getInstance(): CrashHandler {
            return instance
        }
    }

    fun init(context: Context) {
        mContext = context
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler()
        Thread.setDefaultUncaughtExceptionHandler(this)
    }

    override fun uncaughtException(thread: Thread, ex: Throwable) {
        if (!handleException(ex) && mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler?.uncaughtException(thread, ex)
        }
    }

    private fun handleException(ex: Throwable?): Boolean {
        if (ex == null) return false

        try {
            // 收集设备和错误信息
            val errorInfo = collectErrorInfo(ex)
            
            // 在主线程显示错误对话框
            Thread {
                Looper.prepare()
                showCrashDialog(errorInfo)
                Looper.loop()
            }.start()

            return true
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }
    }

    private fun collectErrorInfo(ex: Throwable): String {
        val sb = StringBuilder()
        
        // 添加设备信息
        sb.append("设备信息：\n")
        sb.append("设备型号：${Build.MODEL}\n")
        sb.append("Android版本：${Build.VERSION.RELEASE}\n")
        sb.append("系统版本号：${Build.VERSION.SDK_INT}\n")
        sb.append("制造商：${Build.MANUFACTURER}\n")
        
        // 添加时间信息
        val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
            .format(Date())
        sb.append("崩溃时间：$time\n\n")
        
        // 添加异常信息
        sb.append("异常信息：\n")
        sb.append("${ex.message}\n\n")
        
        // 添加堆栈跟踪
        sb.append("堆栈跟踪：\n")
        val sw = StringWriter()
        val pw = PrintWriter(sw)
        ex.printStackTrace(pw)
        sb.append(sw.toString())
        
        return sb.toString()
    }

    private fun showCrashDialog(errorInfo: String) {
        mContext?.let { context ->
            val dialogView = LayoutInflater.from(context)
                .inflate(R.layout.dialog_crash, null)
            
            val tvErrorMessage = dialogView.findViewById<TextView>(R.id.tvErrorMessage)
            tvErrorMessage.text = errorInfo
            
            val dialog = AlertDialog.Builder(context)
                .setView(dialogView)
                .setCancelable(false)
                .create()

            // 设置按钮点击事件
            dialogView.findViewById<TextView>(R.id.btnRestart).setOnClickListener {
                dialog.dismiss()
                restartApp()
            }

            dialogView.findViewById<TextView>(R.id.btnExit).setOnClickListener {
                dialog.dismiss()
                exitApp()
            }

            // 保存错误日志
            saveErrorLog(errorInfo)

            // 显示对话框
            if (context is Activity && !context.isFinishing) {
                dialog.show()
            }
        }
    }

    private fun saveErrorLog(errorLog: String) {
        // 这里可以将错误日志保存到文件或发送到服务器
        // TODO: 实现错误日志的保存逻辑
    }

    private fun restartApp() {
        try {
            mContext?.let { context ->
                val intent = context.packageManager
                    .getLaunchIntentForPackage(context.packageName)
                intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                intent?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                context.startActivity(intent)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            exitApp()
        }
    }

    private fun exitApp() {
        android.os.Process.killProcess(android.os.Process.myPid())
        exitProcess(1)
    }
} 